var mongoose = require('mongoose'),
  Schema = mongoose.Schema,
  ObjectId = Schema.ObjectId,
  config = require('./config'),

  //数据库信息
  host = config.IS_LOCAL ? 'localhost' : config.DB_HOST,
  port = config.IS_LOCAL ? '27017' : config.DB_PORT,
  database = config.IS_LOCAL ? 'user' : config.DB_NAME,
  user = config.IS_LOCAL ? '' : config.DB_USER,
  pass = config.IS_LOCAL ? '' : config.DB_PASS,

  connection = mongoose.createConnection(),
  options = {
    db: { native_parser: true },
    server: { poolSize: 5 },
    user: user,
    pass: pass
  },
  UserModel;

  //mongoose调试
  config.MONGOOSE_DEBUG && mongoose.set('debug', true);

  //断开的时候再打开，保持长连接，用于BAE上，因为BAE默认30秒断开一次
  function openDb(callback){

    console.log('opening db of '+ database +' ... ');

    connection.open(host, database, port, options, callback);
  };

  connection.on('error', function (err) {

	console.log("db connection : " + err);
    connection.close();

  });

  openDb();

  //设置用户模型
  UserModel = new Schema({
    id: ObjectId,
    account: Number,
    pass: String,
    sid: String,
    sig: String,  //获取验证码和检查验证码所需
    cap_cd: String, //需要输入验证码前，获取验证码所需
    date: Number
  });

module.exports = {
  connection: connection,
  openDb: openDb,
  UserModel: UserModel
};